package com.siemens.industrial.web.mvc.controller.admin;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.siemens.industrial.model.JobType;
import com.siemens.industrial.model.admin.*;
import com.siemens.industrial.utils.*;
import com.siemens.industrial.web.mvc.dao.admin.UserDao;
import com.siemens.industrial.web.mvc.pojo.DataTableQuery;
import com.siemens.industrial.web.mvc.pojo.TenantServiceItem;
import com.siemens.industrial.web.mvc.service.AuthService;
import com.siemens.industrial.web.mvc.service.WriteLogs;
import com.siemens.industrial.web.mvc.service.admin.*;
import com.siemens.industrial.web.mvc.service.partner.PartnerUserService;
import org.apache.http.HttpEntity;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.util.EntityUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by qupen on 2016/9/1.
 */
@Controller
public class UserController {
    private static final ObjectMapper objectMapper = new ObjectMapper();
    @Resource
    UserService userService;

    @Resource
    PasswordEncoder passwordEncoder;

    @Resource
    PartnerUserService partnerUserService;

    @Resource
    EventService eventService;

    @Resource
    UserDao userDao;

    @Resource
    AuthService authService;

    @Resource
    SystemConfigService systemConfigService;

    @Resource
    WriteLogs writeLogs;

    @Resource
    TenantService tenantService;

    @Resource
    ServeService serveService;

    @Resource
    JdbcTemplate jdbcTemplate;

    @RequestMapping(value = "/setup", method = RequestMethod.GET)
    @ResponseBody
    public String setAdmin() {
        User user = new User();
        user.setUserId(UUIDGenerator.getUUID());
        user.setRoleId(0);
        user.setUserPwd(passwordEncoder.encode("admin"));
        user.setEnabled(1);
        user.setUserName("admin");
        userDao.save(user);

        List<Map<String, Object>> events = Definition.EVENT.getData();
        for (Map<String, Object> o : events) {
            Event event = new Event();
            event.setEventId(o.get("event_id").toString());
            event.setEventName(o.get("event_name").toString());
            event.setEventType(o.get("event_type").toString());
            event.setEventDesc(o.get("event_desc").toString());
            event.setEnabled(Integer.parseInt(o.get("enabled").toString()));

            eventService.saveEvent(event);
        }

        List<Map<String, Object>> serviceList = Definition.SERVICE.getData();
        for (Map<String, Object> o : serviceList) {
            Service service = new Service();
            service.setService_id(o.get("service_id").toString());
            service.setService_name(o.get("service_name").toString());
            service.setService_desc(o.get("service_desc").toString());
            service.setEnabled(Integer.parseInt(o.get("enabled").toString()));
            serveService.save(service);
        }
        return "SUCCESS";
    }

    @RequestMapping(value = "/admin/userCount", method = RequestMethod.GET)
    public String getUserAccount(Map<String, Object> map) {

        map.put("userAccount", userService.getUserAccount());
        return "admin/index";
    }

    @RequestMapping(value = "/admin/user/users", method = RequestMethod.GET)
    public String getUserListPage() {
        return "admin/user_list";
    }

//    @RequestMapping(value = "/admin/api/v1/user/list", method = RequestMethod.GET)
//    @ResponseBody
//    public Map<String, Object> getUserList() {
//        List<User> users = userService.getUserList();
//
//        return RestResponse.create(GlobalResponseCode.SUCCESS).putData(users).build();
//    }

    @RequestMapping(value = "/admin/api/v1/user/list", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getUserList(HttpServletRequest request) {
        DataTableQuery dt = new DataTableQuery(request);
        if (dt.isDataTableRequest()) {
            Map<String, Object> map = userService.getUserListByDataTable(request);
            return map;
        } else {
            return dt.buildResponse(0, 0, new ArrayList<>());
        }
    }

    @RequestMapping(value = "/admin/user/setInfo", method = RequestMethod.GET)
    public String getUpdateUserPage(@RequestParam(name = "id") String userId, ModelMap modelMap) {
        User user = userService.getUserByUserId(userId);
        modelMap.put("userInfo", user);
        return "admin/updateUser";
    }

    @RequestMapping(value = "/admin/api/v1/user/initPassword", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> initUserPassword(@RequestBody Map<String, Object> data) {
        String password = PasswordUtil.get(8);
        System.out.print(password);
        int i = userService.resetPassword(passwordEncoder.encode(password), data.get("userId").toString());
        if (i == 1) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            User currentUser = (User) authService.currentUser();
            User user = userService.getUserByUserId(data.get("userId").toString());
            String content = currentUser.getUserName() + "于" + simpleDateFormat.format(new Date()) + "重置了用户\"" + user.getUserName() + "\"的密码。";
            writeLogs.writeLog(SystemConfig.LOG_USER_OPERATE_KEY, content, "platform_operate");
            return RestResponse.create(GlobalResponseCode.SUCCESS).putData(password).build();
//            String email = userService.getUserByUserId(data.get("userId").toString()).getEmail();
//            return systemConfigService.sendMail(email,"重置密码","新密码为："+password);
        }

        return RestResponse.create(GlobalResponseCode.ERROR_RESET_PASSWORD_FAIL).build();
    }

    @RequestMapping(value = "/admin/api/v1/user/setEnabled", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> setEnabled(@RequestBody Map<String, Object> data) throws javax.mail.MessagingException {
        userService.enableOrDisable(data.get("userId").toString(), Integer.parseInt(data.get("enabled").toString()));
        User currentUser = (User) authService.currentUser();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String content = currentUser.getUserName() + "于" + simpleDateFormat.format(new Date());
        User user = userService.getUserByUserId(data.get("userId").toString());
        if (Integer.parseInt(data.get("enabled").toString()) == 0) {
            String userId = ((User) authService.currentUser()).getUserId();
            String info = "{\"userId\":\"" + data.get("userId").toString() + "\",\"currentUser\":\"" + userId + "\",\"type\":\"userUnEnabled\"}";
            SocketClient socketClient = new SocketClient();
            socketClient.sendMessage(JobType.Event.toString(), info);
            content = content + "禁用了用户" + "\"" + user.getUserName() + "\"";
        } else if (Integer.parseInt(data.get("enabled").toString()) == 1) {
            content = content + "启用了用户" + "\"" + user.getUserName() + "\"";
        } else {
            content = content + "删除了用户" + "\"" + user.getUserName() + "\"";
        }
        writeLogs.writeLog(SystemConfig.LOG_USER_OPERATE_KEY, content, "platform_operate");
        return RestResponse.create(GlobalResponseCode.SUCCESS).build();
    }

    @RequestMapping(value = "/admin/api/v1/user/setInformation", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> setInformation(@RequestBody Map<String, Object> data) throws SiemensException {
        userService.updateUser(data);
        User currentUser = (User) authService.currentUser();
        User user = userService.getUserByUserId(data.get("userId").toString());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String content = currentUser.getUserName() + "于" + simpleDateFormat.format(new Date()) + "更新了管理员\"" + user.getUserName() + "\"的信息。";
        writeLogs.writeLog(SystemConfig.LOG_USER_OPERATE_KEY, content, "platform_operate");
        return RestResponse.create(GlobalResponseCode.SUCCESS).build();
    }

    @RequestMapping(value = "/admin/user/createUser", method = RequestMethod.GET)
    public String getCreateUserPage() {
        return "admin/createUser";
    }

    @RequestMapping(value = "/admin/api/v1/user/addUser", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> createUser(@RequestBody Map<String, Object> data) {
        String userId = UUIDGenerator.getUUID();
        String password = PasswordUtil.get(8);
        try {
            userService.saveUser(data, passwordEncoder.encode(password), userId);
            User user = userService.getUserByUserId(userId);
//            String mail = user.getEmail();
//            systemConfigService.sendMail(mail,"平台管理员初始密码","密码为:"+password);
            User currentUser = (User) authService.currentUser();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String content = currentUser.getUserName() + "于" + simpleDateFormat.format(new Date()) + "创建了用户" + "\"" + user.getUserName() + "\"";
            writeLogs.writeLog(SystemConfig.LOG_USER_OPERATE_KEY, content, "platform_operate");
            return RestResponse.create(GlobalResponseCode.SUCCESS).putData(password).build();
        } catch (SiemensException e) {
            e.printStackTrace();
            return RestResponse.create(GlobalResponseCode.ERROR_USER_NOT_CREATE).build();
        }
    }

    @RequestMapping(value = "/admin/api/v1/user/checkName", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> checkUserName(String userName) {
        boolean isExist = userService.getUserByUserName(userName);

        return RestResponse.create(GlobalResponseCode.SUCCESS).putData(isExist).build();
    }

    @RequestMapping(value = "/admin/user/childrenUsers", method = RequestMethod.GET)
    public String getChildrenUserPage(String id, String tenantKey, ModelMap modelMap) {
        modelMap.put("tenantId", id);
        modelMap.put("tenantKey", tenantKey);
        return "admin/childrenUser_list";
    }

    //子账户列表
    @RequestMapping(value = "/admin/api/v1/tenant/userList", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getChildrenUsers(String tenantId, String tenantKey) {
        List<com.siemens.industrial.model.partner.User> users = partnerUserService.getUsers(tenantKey, tenantId);

        return RestResponse.create(GlobalResponseCode.SUCCESS).putData(users).build();
    }

    //启用or禁用子账户
    @RequestMapping(value = "/admin/api/v1/tenantUser/setEnabled", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> setServiceEnabled(@RequestParam(name = "tenantId") String tenantId, @RequestParam(name = "enabled") int enabled, @RequestParam(name = "tenantUserId") String tenantUserId) {
        partnerUserService.setTenantUserEnabled(tenantId, enabled, tenantUserId);
        User currentUser = (User) authService.currentUser();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String content = currentUser.getUserName() + "于" + simpleDateFormat.format(new Date());

        Tenant tenant = tenantService.getTenant(tenantId);
        com.siemens.industrial.model.partner.User tUser = partnerUserService.getUser(tenant.getTenantKey(), tenantId, tenantUserId);
        if (enabled == 0) {
            String userId = ((User) authService.currentUser()).getUserId();
            String info = "{\"currentUser\":\"" + userId + "\",\"tenantId\":\"" + tenantId + "\",\"tenantUserId\":\"" + tenantUserId + "\",\"type\":\"tenantUserUnEnabled\"}";
            SocketClient socketClient = new SocketClient();
            socketClient.sendMessage(JobType.Event.toString(), info);
            content = content + "禁用了租户" + "\"" + tenant.getTenantName() + "\"" + "的管理员\"" + tUser.getUserName() + "\"";
        } else if (enabled == 1) {
            content = content + "启用了租户" + "\"" + tenant.getTenantName() + "\"" + "的管理员\"" + tUser.getUserName() + "\"";
        }
        writeLogs.writeLog(SystemConfig.LOG_USER_OPERATE_KEY, content, "platform_operate");
        return RestResponse.create(GlobalResponseCode.SUCCESS).build();
    }

    @RequestMapping(value = "/admin/changePassword", method = RequestMethod.GET)
    public String changePasswordPage() {
        return "admin/changePassword";
    }

    @RequestMapping(value = "/admin/api/v1/changePassword", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> changePassword(@RequestBody Map<String, String> data) {
        User loginUser = (User) authService.currentUser();
        if (!passwordEncoder.matches(data.get("oldPassword"), loginUser.getPassword())) {
            return RestResponse.create(GlobalResponseCode.ERROR_INCORRECT_PASSWORD).build();
        } else {
            loginUser.setUserPwd(passwordEncoder.encode(data.get("newPassword")));
        }

        userService.resetPassword(loginUser.getPassword(), loginUser.getUserId());

        return RestResponse.create(GlobalResponseCode.SUCCESS).build();
    }

    @RequestMapping(value = "/admin/api/v1/messageCount", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getMessageCount() {
        User loginUser = (User) authService.currentUser();
        int count = userService.getMessageAccount(loginUser.getUserId());
        return RestResponse.create(GlobalResponseCode.SUCCESS).putData(count).build();
    }

    @RequestMapping(value = "/admin/api/v1/messages", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getMessageList(@RequestParam(name = "eventType",required = false) String eventType,
                                              @RequestParam(name = "executant",required = false) String executant,
                                              @RequestParam(name = "operands",required = false) String operands,
                                              @RequestParam(name = "service",required = false) String service,
                                              @RequestParam(name = "createTime",required = false) String createTime,
                                              HttpServletRequest request) {
        DataTableQuery dt = new DataTableQuery(request);
        if (dt.isDataTableRequest()){
            Map map = userService.getAllMessageByDataTable(eventType,executant,operands,service,createTime,request);
            return map;
        }
        return dt.buildResponse(0,0,new ArrayList<>());
    }

    @RequestMapping(value = "/admin/user/messages", method = RequestMethod.GET)
    public String getChildrenUserPage(ModelMap modelMap) {
        List<Event> events = eventService.getEvents();
        List<Service> services = serveService.getServiceList();
        modelMap.put("events",events);
        modelMap.put("services",services);
        return "admin/message_list";
    }

    @RequestMapping(value = "/admin/api/v1message/getExecutant", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getDistanctExecutant(String str) {
       List<Map<String,Object>> list = userService.getMessageDistanctExecutant(str);
        return RestResponse.create(GlobalResponseCode.SUCCESS).putData(list).build();
    }

    @RequestMapping(value = "/admin/api/v1/message/getOperands", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getDistanctOperands(String str) {
        List<Map<String,Object>> list = userService.getMessageDistanctOperands(str);
        return RestResponse.create(GlobalResponseCode.SUCCESS).putData(list).build();
    }
}
